﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.Commerce.Contexts.Promotions;

namespace Kooboo.Commerce
{
    public class PromotionContext
    {
        public PromotionContext()
        {
            this.ErrorMessages = new List<string>();
            this.Items = new List<PromotionItem>();
        }

        public List<string> ErrorMessages
        {
            get;
            set;
        }
  
        public List<PromotionItem> Items
        {
            get;
            set;
        }

        public decimal Total
        {
            get;
            set;
        }

        public decimal Discount
        {
            get;
            set;
        }

        public decimal TaxAllowance
        {
            get;
            set;
        }

        public decimal ShippingAllowance
        {
            get;
            set;
        }

        public decimal PaymentAllowance
        {
            get;
            set;
        }

        public String CouponCode { get; set; }

        public void Execute()
        {
            var host = new ServiceHost();
            var rules = host.QueryPromotionRules().Where(i=>i.IsEnable).OrderByDescending(i=>i.Priority).ToList();

            while (rules.Count > 0)
            {
                var rule = rules[0];
                var promotion = rule.FindPromotion();
                if (promotion != null)
                {
                    if (promotion.Execute(rule, null, this))
                    {
                        foreach (var i in rule.KillRules)
                        {
                            rules.Remove(i);
                        }
                    }
                }


                rules.Remove(rule);
            }
        }
    }

    public class PromotionItem
    {
        public IProduct Product
        {
            get;
            set;
        }

        public decimal SubTotal
        {
            get;
            set;
        }

        public decimal Discount
        {
            get;
            set;
        }

        public int Quantity
        {
            get;
            set;
        }

        public bool IsDiscounted
        {
            get;
            set;
        }

        public object RelatedObject
        {
            get;
            set;
        }
    }
}
